#include "event_loop.h"
#include <stdio.h>


namespace rr {
namespace nio {

EventLoop::EventLoop()
{
    printf("EventLoop::EventLoop() this[%p]\n", this);
    event_recorder_ = std::make_shared<EventRecorder>();
    loop_ = new uv_loop_t();
    uv_loop_init(loop_);

    async_ = std::make_shared<EventAsync>(this);
}

EventLoop::~EventLoop()
{
    if(loop_ != nullptr) {
        uv_loop_close(loop_);
        delete loop_;
        loop_ = nullptr;
    }
    printf("EventLoop::~EventLoop() this[%p]\n", this);
}

int32_t EventLoop::Loop()
{   
    async_->Start();
    int32_t ret = uv_run(loop_, UV_RUN_DEFAULT);
    printf("EventLoop::Loop() run end this[%p]\n", this);
    event_recorder_->Dump();
    return ret;
}

void EventLoop::Quit()
{
    printf("EventLoop::Quit() begin this[%p]\n", this);
    //uv_stop(loop_);
    RunInLoop([this]() {
        event_recorder_->Dump();
        async_->Close(nullptr);
    });
    
    printf("EventLoop::Quit() end this[%p]\n", this);
}

void EventLoop::RunInLoop(const PendingCallback& cb)
{
    async_->submit(cb);
}


} //namespace 
} //namespace 
